package com.jcl.recruit.console.login.service;

import com.jcl.core.security.service.UserDetailService;
import com.jcl.core.security.utils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

/**
 * @ClassName LoginService
 * @Author yyliu
 * @Date 2018/12/20 9:30
 * @Version 1.0
 **/
@Service
public class LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    @Qualifier("userDetailService")
    private UserDetailService userDetailService;

    public String login(String username, String password) {
        UsernamePasswordAuthenticationToken upToken = new UsernamePasswordAuthenticationToken(username, password);
        Authentication authentication = authenticationManager.authenticate(upToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        UserDetails userDetails = userDetailService.loadUserByUsername(username);
        return JwtTokenUtil.generateToken(userDetails);
    }

    public String refreshToken(String oldToken) {
        String token = oldToken.substring("Bearer ".length());
        if (!JwtTokenUtil.isExpiration(token)) {
            return JwtTokenUtil.refreshToken(token);
        }
        return "error";
    }

}
